package com.zb.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zb.bean.Article;
import com.zb.bean.Navigation;
import com.zb.qo.ArticleQo;
import com.zb.service.ArticleService;
import com.zb.service.NavigationService;
import com.zb.util.LoggerUtil;
import com.zb.vo.AjaxResult;
import com.zb.vo.ArticleVo;
import com.zb.vo.EditorFileListVo;
import com.zb.vo.EditorFileVo;
import com.zb.vo.EditorImgListVo;
import com.zb.vo.EditorImgVo;
import com.zb.vo.PageResult;
import com.zb.vo.PageVo;

/**
 * 文章控制器
 * 
 * 作者: zhoubang 日期：2015年4月1日 下午5:30:51
 */
@Controller
@RequestMapping("/article")
public class ArticleController extends BaseController {

    
    @Resource(name="articleServiceImpl")
    private ArticleService articleService;

    @Resource(name="navigationServiceImpl")
    private NavigationService navigationService;
    public static void main(String[] args) {
        int a = 4;
        if(a > 1){
            System.out.println("1");
        }else if(a >2){
            System.out.println(2);
        }else{
            System.out.println(4);
        }
    }
    /**
     * 发布文章
     * 
     * @param req
     * @param res
     * @param article
     * @return
     * @throws IOException
     */
    @RequiresPermissions(value="article:add")
    @RequestMapping("/saveArticle")
    @ResponseBody
    public AjaxResult<String> saveArticle(HttpServletRequest req,
            HttpServletResponse res, Article article) throws IOException {
        LoggerUtil.LoggerFormatPattern("/saveArticle-发布文章，article信息：{0}", article.toString());
        
        AjaxResult<String> ajaxResult = new AjaxResult<String>();

        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        article.setAvailable(1);
        try {
            articleService.saveArticle(article);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setMsg("保存数据出现异常");
        }
        return ajaxResult;
    }

    /**
     * 
     * 获取文章列表
     * 
     * @param req
     * @param res
     * @param articleQo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getArticleList", method = RequestMethod.GET)
    public ModelAndView getArticleList(HttpServletRequest req,
            HttpServletResponse res, ArticleQo articleQo) throws Exception {
        LoggerUtil.LoggerFormatPattern("/getArticleList-获取文章列表:请求参数articleQo信息:{0}", articleQo.toString());
        
        ModelAndView mav = modelAndView("/index");

        PageVo<Article> articleList = articleService.getArticleList(articleQo);
        mav.addObject(articleList);
        mav.addObject(articleQo);
        mav.addObject("address",getParentNames(articleQo.getNavigationId()));
        return mav;
    }

    /**
     * 读取显示文章详细内容
     * 
     * 作者: zhoubang 日期：2015年4月17日 下午3:32:39
     * 
     * @param req
     * @param res
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/articleDetail/{id}", method = RequestMethod.GET)
    public ModelAndView articleDetail(HttpServletRequest req,
            HttpServletResponse res, @PathVariable(value = "id") String id) throws Exception {
        Article article = articleService.loadArticleContent(id);

        ModelAndView mav = modelAndView("/user/articleDetail");
        mav.addObject("article", article);
        mav.addObject("address",getParentNames(article.getNavigationId()));
        return mav;
    }
    
    /**
     * 后台文章管理-进入文章列表view
     * 
     * 作者: zhoubang 
     * 日期：2015年5月8日 上午8:44:39
     * @param req
     * @param res
     * @return
     * @throws Exception
     */
    @RequiresPermissions(value="article:list")
    @RequestMapping(value = "/articleListView", method = RequestMethod.GET)
    public ModelAndView articleListView(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ModelAndView mav = modelAndView("/admin/article/list");
        //获取所有父模块
        List<Navigation> models = articleService.getArticleModels();
        mav.addObject("models", models);
        return mav;
    }
    
    /**
     * 后台文章管理-文章列表
     * 
     * 作者: zhoubang 
     * 日期：2015年5月8日 上午8:54:43
     * @param req
     * @param res
     * @param articleQo
     * @return
     * @throws Exception 
     */
    @RequiresPermissions(value="article:list")
    @RequestMapping(value = "/articleList", method = RequestMethod.GET)
    @ResponseBody
    public PageResult<ArticleVo> articleList(HttpServletRequest req, HttpServletResponse res,ArticleQo articleQo) throws Exception{
        PageVo<Article> articleList = articleService.getArticleList(articleQo);
        return new PageResult<ArticleVo>(articleList.getTotalSize(), ArticleVo.buildArticleList(articleList.getResult()));
    }
    
    /**
     * 后台文章管理-进入编辑文章view
     * 
     * 作者: zhoubang 
     * 日期：2015年5月8日 上午10:26:27
     * @param req
     * @param res
     * @param articleId
     * @return
     * @throws Exception
     */
    @RequiresPermissions(value="article:edit")
    @RequestMapping(value = "/editArticleView", method = RequestMethod.GET)
    public ModelAndView editArticleView(HttpServletRequest req, HttpServletResponse res,String articleId) throws Exception {
        ModelAndView mav = modelAndView("/admin/article/view");
        //文章内容
        Article article = articleService.loadArticleContent(articleId);
        
        //模块列表
        List<Navigation> ls = articleService.getArticleModels();
        
        mav.addObject("article", article);
        mav.addObject("models", ls);
        return mav;
    }
    
    /**
     * 更新文章信息
     * 
     * 作者: zhoubang 
     * 日期：2015年5月8日 上午10:52:38
     * @param req
     * @param res
     * @param article
     * @return
     */
    @RequiresPermissions(value="article:edit")
    @RequestMapping(value = "/updateArticle", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult<String> updateArticle(HttpServletRequest req, HttpServletResponse res,Article article){
        AjaxResult<String> result = new AjaxResult<String>();
        try {
            articleService.updateArticle(article);
        } catch (Exception e) {
            result.setCode(500);
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 进入发布文章view
     * 
     * 作者: zhoubang 
     * 日期：2015年5月12日 下午3:21:24
     * @param req
     * @param res
     * @return
     * @throws Exception 
     */
    @RequiresPermissions("article:add")
    @RequestMapping("toAddArticle")
    public ModelAndView toAddArticle(HttpServletRequest req, HttpServletResponse res) throws Exception{
        ModelAndView mav = new ModelAndView("/admin/article/add");
        List<Navigation> modelSubList = navigationService.getModuleSub();
        mav.addObject("modelSubList", modelSubList);
        return mav;
    }
    
    /**
     * 删除文章
     * 
     * 作者: zhoubang 
     * 日期：2015年5月21日 上午9:32:20
     * @param articleId
     * @return
     */
    @RequestMapping("delArticle")
    @RequiresPermissions("article:edit")
    @ResponseBody
    public AjaxResult<String> delArticle(String articleId){
        AjaxResult<String> result = new AjaxResult<String>();
        try {
            Article article = articleService.load(articleId);
            article.setAvailable(0);
            articleService.updateArticle(article);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }
    
    /**
     * 在线管理-获取所有图片资源的列表
     * @return
     */
    @ResponseBody
    @RequestMapping("imageListManage")
    public EditorImgListVo imageListManage(HttpServletRequest req, HttpServletResponse res){
        EditorImgListVo vo = new EditorImgListVo();
        List<EditorImgVo> list = new ArrayList<EditorImgVo>();
        vo.setStart(0);
        vo.setState("SUCCESS");
        
        String path = req.getSession().getServletContext().getRealPath("/");
        String imgPath = "/resources/attached/image/";
        
        String baseUrl = req.getScheme() + "://" + req.getServerName() +":" + req.getServerPort()+ req.getContextPath();
        
        File files = new File(path + imgPath);
        File[] ls = files.listFiles();
        if(ls != null){
            for (int i = 0; i < ls.length; i++) {
                EditorImgVo imgVo = new EditorImgVo();
                imgVo.setMtime("20155210");
                imgVo.setUrl(baseUrl + imgPath + ls[i].getName());
                list.add(imgVo);
            }
        }
        vo.setList(list);
        if(ls != null){
            vo.setTotal(ls.length);
        }else{
            vo.setTotal(0);
        }
        return vo;
    }
    
    
    /**
     * 指定目录下文件列表
     * 
     * 作者: zhoubang 
     * 日期：2015年5月29日 下午3:53:14
     * @param req
     * @param res
     * @return
     */
    @ResponseBody
    @RequestMapping("fileListManage")
    public EditorFileListVo fileListManage(HttpServletRequest req, HttpServletResponse res){
        EditorFileListVo vo = new EditorFileListVo();
        List<EditorFileVo> list = new ArrayList<EditorFileVo>();
        vo.setStart(0);
        vo.setState("SUCCESS");
        
        String path = req.getSession().getServletContext().getRealPath("/");
        String imgPath = "/resources/attached/file/";
        
        String baseUrl = req.getScheme() + "://" + req.getServerName() +":" + req.getServerPort()+ req.getContextPath();
        
        File files = new File(path + imgPath);
        File[] ls = files.listFiles();
        if(ls != null){
            for (int i = 0; i < ls.length; i++) {
                EditorFileVo imgVo = new EditorFileVo();
                imgVo.setState("SUCCESS");
                imgVo.setUrl(baseUrl + imgPath + ls[i].getName());
                list.add(imgVo);
            }
        }
        vo.setList(list);
        if(ls != null){
            vo.setTotal(ls.length);
        }else{
            vo.setTotal(0);
        }
        return vo;
    }
}
